package com.kk.springcloud.controller;

import com.kk.springcloud.entities.CommonResult;
import com.kk.springcloud.entities.Payment;
import com.kk.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
/*
 * @Description:
 * @Author:         阿K
 * @CreateDate:     2022/1/16 18:11
 * @Param:
 * @Return:
 **/
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeOut()
    {
        System.out.println("*****paymentFeignTimeOut from port: "+serverPort);
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return serverPort;
    }


    /**
     * 自定义负载均衡
     * @return
     */
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB()
    {
        return serverPort;
    }

    /**
     * 查看注册服务的信息
     *
     * @return
     */
    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        // 目前已经注册的微服务列表
        List<String> services = discoveryClient.getServices ( );
        for (String element : services) {
            log.info (element);
        }

        // 根据名称获取的微服务实例（就像类和对象的关系）
        List<ServiceInstance> instances = discoveryClient.getInstances ("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance element : instances) {
            log.info (element.getServiceId ( ) + "\t" + element.getHost ( ) + "\t" + element.getPort ( ) + "\t"
                    + element.getUri ( ));
        }
        return this.discoveryClient;
    }


    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create (payment);
        log.info ("*****插入结果1：" + result + "111");
        if (result > 0) {  //成功
            return new CommonResult (200, "插入数据库成功", result);
        } else {
            return new CommonResult (444, "插入数据库失败", null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById (id);
        log.info ("*****查询结果：" + payment);
        if (payment != null) {  //说明有数据，能查询成功
            return new CommonResult (200, "查询成功8081", payment);
        } else {
            return new CommonResult (444, "没有对应记录，查询ID：" + id, null);
        }
    }
}

